package com.edu.service.impl;

import cn.hutool.core.util.IdUtil;
import com.edu.common.*;
import com.edu.service.EbookService;
import com.edu.util.CopyUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.edu.pojo.Ebook;
import com.edu.pojo.EbookExample;

import java.util.List;
import java.util.stream.Collectors;

import com.edu.dao.EbookMapper;
import org.springframework.util.ObjectUtils;

@Service
public class EbookServiceImpl implements EbookService {

    @Resource
    private EbookMapper ebookMapper;

    @Resource
    private SnowFlake snowFlake;


    @Override
    public List<Ebook> getAll() {
        return ebookMapper.selectByExample(null);
    }

    @Override
    public PageResp<EbookResp> getEbook(EbookReq ebookReq) {
        PageResp<EbookResp> pageResp = new PageResp<>();
        //开始查询
        EbookExample ebookExample = new EbookExample();
        EbookExample.Criteria criteria = ebookExample.createCriteria();
        if (ebookReq.getName() != null) {
            criteria.andNameLike("%" + ebookReq.getName() + "%");
        }
        PageHelper.startPage(ebookReq.getPage(), ebookReq.getSize());
        //返回查询结果
        List<Ebook> ebooks = ebookMapper.selectByExample(ebookExample);
        //类型转换
        List<EbookResp> ebookRespList = ebooks.stream().map(ebook -> {
            EbookResp ebookResp = new EbookResp();
            ebookResp.setId(ebook.getId());
            ebookResp.setName(ebook.getName());
            ebookResp.setCategory1Id(ebook.getCategory1Id());
            ebookResp.setCategory2Id(ebook.getCategory2Id());
            ebookResp.setDescription(ebook.getDescription());
            ebookResp.setCover(ebook.getCover());
            ebookResp.setViewCount(ebook.getViewCount());
            ebookResp.setVoteCount(ebook.getVoteCount());
            ebookResp.setDocCount(ebook.getDocCount());
            return ebookResp;
        }).collect(Collectors.toList());
        PageInfo<EbookResp> pageInfo = new PageInfo<>(ebookRespList);
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(ebookRespList);
        return pageResp;
    }

    @Override
    public void save(EbookSaveReq req) {
        Ebook ebook = CopyUtil.copy(req, Ebook.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            // 新增
            ebook.setId(snowFlake.nextId());
            ebookMapper.insert(ebook);
        } else {
            // 更新
            ebookMapper.updateByPrimaryKey(ebook);
        }
    }

    @Override
    public void delete(Long id) {
        ebookMapper.deleteByPrimaryKey(id);
    }
}
